package org.example.JUC;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class CyclicBarrierTest {

    private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(4, () -> System.out.println("Done!"));

    public static void main(String[] args) {

        for (int i = 0; i < 4; i++) {
            new Worker().start();
        }
    }

    static class Worker extends Thread {
        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + "start");
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName() + "end");
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
